import { fetchHome } from '../../services/home/home';
import { fetchGoodsList } from '../../services/good/fetchGoods';
import Toast from 'tdesign-miniprogram/toast/index';
import { getImgLb } from '../../services/config/api';
import { request } from '../../services/_utils/util';
const api = require('../../services/config/api');

Page({
  data: {
    imgSrcs: [],
    imgSrcsId: [],
    nodata: ['http://127.0.0.1:8021/img/coment/nodata.png'],
    imgsData: [],
    tabList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    formdata: {},
    TemplateID: 'accept',
    isok: false,
    placedata: [],
    placeId: 1,
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {
    this.getTabBar().init();
    this.InitializationData();
  },

  InitializationData() {
    var isok = false;
    if (Object.keys(wx.getStorageSync('TemplateID')).length > 0 && wx.getStorageSync('TemplateID') == 'accept') {
      isok = true;
    }
    this.setData({
      isok: isok,
    });
  },
  //订阅消息
  subscribe() {
    var that = this;
    var TemplateID = 'c94DRkKCo4QAfnZA36Oqs7V1DMNVvy3by9dF2-FP5ec';
    console.log(TemplateID);
    var TemplateStatus = wx.getStorageSync('TemplateID');
    if (TemplateStatus != 'accept') {
      wx.requestSubscribeMessage({
        tmplIds: [TemplateID],
        complete(res) {
          //订阅
          that.setData({
            'formdata.id': wx.getStorageSync('userInfo').id,
            'formdata.template': TemplateID,
          });
          console.log('complete: ', res);
          request(api.SubscribeMsg, this.data.formdata).then(function (res) {
            wx.setStorageSync('TemplateID', res[TemplateID]);
            that.setData({
              isok: true,
            });
          });
        },
      });
    }
  },

  onLoad() {
    this.init();
    this.selectPlace();
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    fetchHome().then(({ swiper, tabList }) => {
      this.setData({
        tabList,
        pageLoading: false,
      });
      this.loadGoodsList(true);
    });
  },

  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    this.loadGoodsList(true);
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    this.setData({ goodsListLoadStatus: 1 });
    const pageSize = this.goodListPagination.num;
    let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 0;
    }

    try {
      const nextList = await fetchGoodsList(pageIndex, pageSize);

      this.setData({
        // goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
        goodsListLoadStatus: 0,
      });
      this.goodListPagination.index = pageIndex;
      this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({ goodsListLoadStatus: 3 });
    }
  },

  goodListClickHandle(e) {
    var vageId = e.detail.goods.vageId;
    var userId = wx.getStorageSync('userInfo').id;
    if (userId == null || userId == undefined) {
      //跳转到登录页面
      wx.redirectTo({
        url: '/pages/login/index',
      });
    } else {
      wx.navigateTo({
        url: `/pages/goods/details/index?spuId=${vageId}`,
      });
    }
  },
  changePlace(e) {
    console.log(e);
    this.setData({
      placeId: e.detail,
    });
    wx.setStorageSync('placeId', e.detail);
    this.reloadMsg();
    this.reloadimg();
  },
  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },

  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },

  navToActivityDetail({ detail }) {
    console.log(this.data.imgSrcsId);
    console.log(this.data.imgSrcsId[detail.index]);
    // const { index: promotionID = 0 } = detail || {};
    // wx.navigateTo({
    //   url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    // });
  },
  reloadimg() {
    var arr = [];
    var arrId = [];
    var tt = this;
    request(api.getImgLb, { type: 0, placeId: this.data.placeId }).then(function (res) {
      console.log(res);
      var data = res.data;
      data.forEach((res) => {
        res.imgs.forEach((elm) => {
          arr.push(elm);
          arrId.push(res.vageId);
        });
      });
      tt.setData({
        imgSrcs: arr,
        imgSrcsId: arrId,
      });
    });
  },
  reloadMsg() {
    var tt = this;
    request(api.getImgLb, { type: 1, placeId: this.data.placeId }).then(function (res) {
      console.log(res);
      tt.setData({
        goodsList: res.data,
      });
    });
  },
  //地区查询
  selectPlace() {
    var that = this;
    request(api.GetPlace + '?isTrue=true', {}).then(function (res) {
      console.log(res);
      that.setData({
        placedata: res.data,
      });
      wx.setStorageSync('placeId', 1);
      that.reloadimg();
      that.reloadMsg();
    });
  },
});
